<template>
  <div class="app-container">
    <!-- <el-button type="text" @click="dialogVisible = true">添加</el-button> -->
   <!-- <el-card shadow="never"> -->
      <!-- <div slot="header" style="text-align: center;">店铺列表</div> -->
      <!-- 店铺店铺列表-->
      <el-button type="success" @click="addmodel">添加</el-button>
      <div class="tableClass">
        <el-table :data="formdata" v-loading="loading" :header-cell-style="{background:'#eef1f6',color:'#606266'}"
          border style="width: 100%;">
          <el-table-column align="center" prop="id" label="序号" />
          <el-table-column align="center" prop="display_name" label="角色名称" />
          <el-table-column align="center" prop="description" label="角色描述">
            <template slot-scope="scope">
                 <span v-if="scope.row.description != null ">{{scope.row.description}}</span>
                <span v-else style="color: red;">暂无描述</span>
              </template>
            </el-table-column>

         <!-- <el-table-column align="center" prop="display_name" label="角色权限" /> -->
          <el-table-column label="操作" align="center" width="230px">
            <template slot-scope="scope">
              <!-- scope.row 获取整行信息 表示当前单元格 #ff9900ba-->
              <el-button class="btnAppeal" size="small" type="warning" @click="updateMsg(scope.row)">修改</el-button>
              <el-button class="btnAppeal" size="small" type="danger" @click="delMsg(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <br>
        <!-- 分页 -->
        <div style="text-align: center;">
          <el-pagination background layout="prev, pager, next" @current-change="pageChange" :page-size="pageSize"
            :total="totalusers" />
        </div>
      </div>
    <!-- </el-card> -->


    <!-- 添加模态款 -->
    <el-dialog :title="title" :visible.sync="modelMsg" @close="dialogClose">
      <div class="msgDiv">
        <!-- <h3>店铺基础信息</h3> -->
        <div>
          <el-form ref="form" :model="form" label-width="80px">
            <el-form-item v-show="vshow" label="序号">
              <el-input v-model="form.id" disabled></el-input>
            </el-form-item>
            <el-form-item label="角色名称" :required="true">
              <el-input v-model="form.display_name" placeholder="请输入角色名称"></el-input>
            </el-form-item>
            <el-form-item label="角色描述">
              <el-input v-model="form.description" placeholder="请输入角色描述"></el-input>
            </el-form-item>
            <el-form-item label="选择权限" :required="true">
                <div style="text-align: left;">
                  <div v-if="!(form.name==='system_admin')" style="height: 500px;overflow: auto">
                    <el-scrollbar style="height:100%">
                      <el-tree
                      ref="tree"
                      :data="permissionList"
                      show-checkbox
                      node-key="id"
                      :props="defaultProps"
                      :default-checked-keys="defaultCheckedKeyArr"
                      :default-expand-all="false">
                      </el-tree>
                    </el-scrollbar>
                  </div>

                  <div v-else style="color: #d41e1e">该角色拥有全部权限，无法设置</div>

                </div>
              </el-form-item>

            <el-button type="success" @click="addMsg(form)">{{addORupdate}}</el-button>
          </el-form>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        modelMsg: false,
        form: {
          id: "",
          name: '',
          display_name: "",
          description: "",
          permission_id: []
        },
        defaultProps: {
          children: 'children',
          label: 'label'
        },//暂未用到
        defaultCheckedKeyArr:[],
        vshow: false,
        loading: false,
        title: "",
        addORupdate: "",
        formdata: [],
        rolesList: [],
         permissionList: [],
        totalusers: 0, //总行数
        pageSize: 5, //每页几行
        startpage: 1, //起始页
      }
    },
    mounted() {
      this.roleList()
      this.permissionsList()
    },
    methods: {
      //关闭添加框，清空选中值
      dialogClose() {
        if(this.form.name!="system_admin"){
          this.$refs.tree.setCheckedKeys([]);
        }
      },
      permissionsList() {
        let params = {
          "page": 1,
          "limit": 100000
        }
        this.$api.permissionsList(params).then(res => {
          if(res.data.level=="success"){
            this.rolesList = res.data.data
            this.rolesList.forEach((item,index) => {
              let firstData = {
                id: index*-1,
                label: item.group,
                children: []
              }
              item.data.forEach((item2,index2) => {
                firstData.children.push({
                  id: item2.id,
                  label: item2.display_name
                })
              })
              this.permissionList.push(firstData)
            })
          }else{
            this.$message.error(res.data.message)
          }
        })
      },

      //获取分页列表
      roleList() {
        let params = {
          "page": this.startpage,
          "limit": this.pageSize
        }
        //调用后台提供的接口方法
        this.$api.roleList(params).then(res => {
          if (res.data.level == "success") {
            this.formdata = res.data.data
            this.totalusers = res.data.page_info.total
            this.loading = false
          }else{
            this.$message.error(res.data.message)
            this.loading = false
          }

        })
      },
      //分页 pageChange当前页发生改变触发函数
      async pageChange(page) {
        this.startpage = page
        this.loading = true
        //调用获取列表的方法
        this.roleList()
      },
      addmodel() {
        this.modelMsg = true
        this.title = '添加角色信息'
        this.addORupdate = "添加",
          this.vshow = false
        this.form.id = "",
        this.form.name = ''
          this.form.display_name = "",
          this.form.description = "",
        this.form.permission_id = []
        this.defaultCheckedKeyArr = [1]
      },
      //提交店铺入驻申请
      async addMsg(form) {
        let checkNodeList = []
        if(form.name!="system_admin"){
          checkNodeList = this.$refs.tree.getCheckedNodes()
        }
        let list = []
        checkNodeList.forEach((item,index) => {
          if(item.id>0){
            list.push(item.id)
          }
        })
        form.permission_id = list

        //判断带星号的是否为空
        if ((form.display_name  && form.permission_id) == "") {
          this.$message({
            message: "带星号为必填项，请完善信息！",
            type: "warning"
          })
          return false;
        }

        /* 显示加载中。。。 */
        const loadingOne = this.$loading({
          lock: true,
          text: '保存中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        if (form.id > 0) {
          /* 修改 */

          console.log(form)
          await this.$api.setRole(form).then(res => {
            console.log(res)
            this.$message({
              type: res.data.level,
              message: res.data.message
            });
            if (res.data.level == "success") {
              this.roleList()
              loadingOne.close()
              this.modelMsg = false
            } else {
              this.modelMsg = true
              loadingOne.close()
            }

          })
        } else {
          /* 添加 */
          await this.$api.setRole(form).then(res => {
            this.$message({
              type: res.data.level,
              message: res.data.message
            });
            if (res.data.level == "success") {
              this.roleList()
              loadingOne.close()
              this.modelMsg = false
            } else {
              this.modelMsg = true
              loadingOne.close()
            }

          })
        }
        this.modelMsg = false

      },
      //修改弹出框
      async updateMsg(row) {
        this.defaultCheckedKeyArr = []
        this.modelMsg = true
        this.title = '修改角色信息'
        this.addORupdate = "修改",
          this.vshow = true
        this.form.id = row.id,
        this.form.name = row.name
          this.form.display_name = row.display_name,
          this.form.description = row.description

        const dataid = {
          'id': row.id
        }
        let roleids = []
        await this.$api.roleSet(dataid).then(res => {
          roleids = res.data.data.permission_id
        })

        this.defaultCheckedKeyArr = roleids


      },
      //删除店铺信息
      async delMsg(id) {
        let delid = {
          id: id
        }
        await this.$confirm('此操作将永久删除该店铺信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
            const loadingOne = this.$loading({
              lock: true,
              text: '保存中...',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })
          this.$api.delRole(delid).then(res => {

            if (res.data.level == "success") {
              this.$message.success(res.data.message)
              loadingOne.close()
              this.roleList()
            }else{
              this.$message.error(res.data.message)
              loadingOne.close()
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }
    }
  }
</script>
<style scoped="scoped">
  /deep/.el-card__header {
    background-color: #409EFF;
    color: whitesmoke;
  }

  /deep/.el-dialog {
    margin-top: 10vh !important;
    width: 33%;
  }

  .msgDiv {
    width: 80%;
    margin: auto;
    text-align: center;
  }

  .el-input {
    display: flex;
    flex-grow: <2>;
  }
</style>
